//
//  YBTiWenInputController.m
//  孕妙
//
//  Created by Raoy on 16/4/11.
//  Copyright © 2016年 是源科技. All rights reserved.
//
/*
 -----------------------------------------------------------------------------------
 2016-08-30
 郭丰修改体温计连接步骤。增加新的体温器连接协议增加判断模式 根据不同的蓝牙外设通用协议。
 
 
 
 
 
 
 
 
 
 ------------------------------------------------------------------------------------
 */

#import "YBTiWenInputController.h"
#import "YBSelectPickerWindow.h"
#import <CoreBluetooth/CoreBluetooth.h>
typedef NS_ENUM(NSInteger, TiWenScale){
    ralingScale,
    eewenScale
};

@interface YBTiWenInputController ()<UIPickerViewDelegate, UIPickerViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate>
//弹出手动输入窗口
@property (strong, nonatomic) YBSelectPickerWindow *pickerWindow;


@property(nonatomic, strong)CBCentralManager *mgr;
@property(nonatomic, strong)NSMutableArray   *peripherals;
//当前外设
@property(nonatomic, strong)CBPeripheral  *peripheral;
/**
 *
 */
@property (nonatomic, assign) TiWenScale scalePer;

//当前外设的服务和特征
@property(nonatomic, strong)CBCharacteristic    *dataInteractCharacteristic;

@end

@implementation YBTiWenInputController
{
    NSArray *_floatArray;   //选择器小数部分
    NSArray *_intArray; //选择器整数部分
    NSString *selectIntStr;    //获取整数值
    NSString *selectFloatStr;  //获取小数值
    NSString *valueStr;     //设置string格式
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =  SYColor(245, 245, 245);;
    self.title = @"记录体温";
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"YB_backToSupper"  highIcon:nil target:self action:@selector(tiwenclickLeftButtonToSupper2:)];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    [self.rightBtn addTarget:self action:@selector(tiwenrigheBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    if (eewenScale) {
        [self scanBle];
    }
    else{
//        [self.connectCenter startScan];
    }
    
    //开始使用蓝牙设备测量
    [self.startbtn2 addTarget:self action:@selector(openBle:) forControlEvents:UIControlEventTouchUpInside];
    
    //设置小数，整数范围
    _floatArray = @[@"0", @"1", @"2", @"3", @"4",@"5", @"6", @"7",@"8", @"9"];
     NSMutableArray *tempAaary = [NSMutableArray array];
    for (NSInteger index = 35; index <= 42; index++) {
        NSString *str = [NSString stringWithFormat:@"%ld", (long)index];
        [tempAaary addObject:str];
    }
    _intArray = [NSArray arrayWithArray:tempAaary];
    
    //设置日期栏
    [self setTitle:@"请输入体温:" buyTitle:@"购买体温计" indexImage:0];
    //设置体温
    valueStr = @" °C";
    [self createLabel:valueStr];
    
    
    // Do any additional setup after loading the view.
}

//- (void)textBlockzz:(returnValueBlock)block
//{
//    self.strBlock = block;
//}

- (void)tiwenrigheBtnClick:(id)sender
{
    self.fuGaiView.hidden = NO;
    if (_pickerWindow == nil) {
        _pickerWindow = [[YBSelectPickerWindow alloc] init];
        [_pickerWindow setInterFace:@"体温(°C)"];
        [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
        
        
    }else{
    
        _pickerWindow.hidden = NO;
    }
    
//    double delayTime = 1.0;
//    dispatch_time_t  delayTimeSeconds = dispatch_time(DISPATCH_TIME_NOW, delayTime * NSEC_PER_SEC);
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_after(delayTimeSeconds, queue, ^{
//        
    
    
    [_pickerWindow.sureBtn addTarget:self action:@selector(savetiwenDataBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_pickerWindow.cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [_pickerWindow.selectPickerView selectRow:2  inComponent:0 animated:YES];
    [_pickerWindow.selectPickerView selectRow:5  inComponent:1 animated:YES];
    selectIntStr = _intArray[2];
    selectFloatStr = _floatArray[5];
//    });
}

- (void)tiwenclickLeftButtonToSupper2:(id)sender
{
    self.pickerWindow = nil;  //释放内存
//    tiwenOncetoken = 0;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)savetiwenDataBtn:(id)sender
{
    valueStr = nil;
    _pickerWindow.hidden = YES;
    self.fuGaiView.hidden = YES;
    valueStr = [NSString stringWithFormat:@"%@.%@ °C", selectIntStr, selectFloatStr];
    [self createLabel:valueStr];
    [self.view setNeedsDisplay];
    
    [self getUserParmaterData:[NSString stringWithFormat:@"%@.%@", selectIntStr, selectFloatStr] selectionValue:0 gaoxueya:nil];
    
}

- (void)cancelBtnClicked:(id)sender
{
    self.fuGaiView.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"sfeawrr------");
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}


- (void)openBle:(UIButton *)button
{
//    tiwenOncetoken = 0;
    
    if (eewenScale) {
        [self scanBle];
    }
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
         return _intArray.count;
    } else {
         return _floatArray.count;
    }


}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    
    if (component == 0) {
        return  _intArray[row];
    } else {
        
        return  _floatArray[row];
    }
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0) {
        selectIntStr = _intArray[row];
    } else {
        selectFloatStr = _floatArray[row];
    }

}



#pragma mark- 连接蓝牙外设


- (NSMutableArray *)peripherals
{
    if (!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    
    return _peripherals;
}

- (CBCentralManager *)mgr
{
    if (!_mgr){
        
        self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    return _mgr;
}

- (void)scanBle
{
    if (eewenScale) {
        if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
            [self.mgr stopScan];
            self.peripheral = nil;
            self.mgr = nil;
            return;
        }
        [MBProgressHUD showMessage:@"正在搜索设备......"];
        self.startbtn2.isAccessibilityElement = NO;
        
        [self.mgr stopScan];
        [self.mgr scanForPeripheralsWithServices:nil options:nil];
        self.startbtn2.isAccessibilityElement = YES;
    }
}



#pragma mark -- CBCentralManagerDelegate
//检查设备是否支持蓝牙
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:// 蓝牙打开
            NSLog(@"CBCentralManagerStatePoweredOn");
            [self.mgr scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStatePoweredOff://蓝牙关闭
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"State Unsupported");
            break;
            
        default:
            NSLog(@"Central Manager Did Update State");
            break;
    }
    
}


//发现外设
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    
    NSLog(@"发现外设：%@  ", peripheral.name);
    if (eewenScale) {
        if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
            [self.mgr stopScan];
            self.peripheral = nil;
            self.mgr = nil;
            return;
        }
        [MBProgressHUD hideHUD];
        
        
        if (![self.peripherals containsObject:peripheral]) {
            if ([peripheral.name hasPrefix:@"Bluetooth BP"]) {
                _scalePer = eewenScale;
                //设置外设代理
                peripheral.delegate = self;
                [self.peripherals addObject:peripheral];
            }
        }
    }
    NSLog(@"找到了 %@", peripheral.name);
    
    for (CBPeripheral *per in self.peripherals) {
        NSLog(@"外设：%@", per);
        if (per.state == NO) {
            self.peripheral = peripheral;
            [self.mgr connectPeripheral:self.peripheral options:nil];
        }
    }
    
    
}

//连接某个外设的时候调用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"连接外设成功");
    [self.mgr stopScan];
    
    // 查找外设中的所有服务
    //#warning 通过传入一个存放服务UDID的数组进去，过滤掉一些不要的服务
    [peripheral discoverServices:nil];
    
}


#pragma mark - CBPeriperalDelegate

//外设已经查找到的服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"发现服务  %@", peripheral.services);
    // 遍历所有的服务
    for (CBService *service in peripheral.services) {
        // 过滤其他服务, 匹配自己想要的服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF0"]]) {
            
            //#warning 通过传入一个存放特征UDID的数组进去，过滤掉一些不要的特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    
}

//连接断开时
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.peripheral = nil;
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙断开"]];
//    tiwenOncetoken = 0;
    NSLog(@"蓝牙连接已断开");
}

//特征值匹配
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didDiscoverCharacteristicsForService: %@", service.characteristics);
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙连接"]];
    [self.view setNeedsDisplay];
    
    [self.peripherals removeAllObjects];
    // 遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"--%@---", characteristic.UUID);
        
        //过滤不想要的特征
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF1"]]){
            NSLog(@"--已找到特征0xFFF1, 注册监听  ");
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF2"]]) {
            NSLog(@"--已找到特征0xFFF2 ,发数据到外设 ");
            
            double delayTime = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //发送数据到蓝牙外设
                [self requestDatatoBlue:characteristic];
                double delayInSeconds1 = 0.5;
                dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 *NSEC_PER_SEC));
                
                dispatch_after(popTime1, dispatch_get_main_queue(), ^{
                    [self requestDatatoBlue:characteristic];
                    dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 *NSEC_PER_SEC));
                    dispatch_after(popTime2, dispatch_get_main_queue(), ^{
                        [self requestDatatoBlue:characteristic];
                    });
                    
                });
                
            });
            
            
        }
    }
}

//外设接收数据
- (void) requestDatatoBlue:(CBCharacteristic *)achar
{
    Byte bytes[6];
    
    bytes[0] = 0xFE;
    bytes[1] = 0xFD;
    bytes[2] = 0xAA;
    bytes[3] = 0xA0;
    bytes[4] = 0x0D;
    bytes[5] = 0x0A;
    
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:6];
    NSLog(@"发送体温数据给蓝牙: %@",dataa);
    
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

//获取外设发来的数据，不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
    if (error)
    {
        NSLog(@"didUpadateValueForCharacteristicError: %@", error.localizedDescription);
        return;
    }
    
    [self.mgr stopScan];
    //外设发数据过来
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF1"]]) {
        NSLog(@"接受数据");
        
        [self analyzeData:characteristic.value withPeripheral:peripheral];
        
        //接受到蓝牙数据 先分析，再回传给设备 最后发送指令关机
        
        NSLog(@"--%@---", characteristic.value);
        
    }
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jiance) name:nil object:nil];
    
    
    
}

//app发送关机指令，使设备关机，反馈指令关闭app
- (void)changeUpdateStateAndCloseBLE
{
    NSLog(@"发送关机指令");
    Byte bytes[6];
    bytes[0] = 0xFE;
    bytes[1] = 0xFD;
    bytes[2] = 0xAA;
    bytes[3] = 0x91;
    bytes[4] = 0x0D;
    bytes[5] = 0x0A;
    
    [self.peripheral writeValue:[NSData dataWithBytes:bytes length:8] forCharacteristic:self.dataInteractCharacteristic type:CBCharacteristicWriteWithResponse];
    
}

//app发数据到蓝牙，是否接收到，没有则0.5s后重新发，最多发三次
- (void)jiance
{
    //    if (self.mgr.state == CBCentralManagerStatePoweredOff) {
    //        sleep(0.5);
    //        dispatch_once(&onceToken1, ^{
    //            self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //        });
    //
    //    }
    
    for (int i = 0; i < 3; i ++) {
        sleep(0.5);
        if (self.mgr.state == CBCentralManagerStatePoweredOff) {
            self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        }
    }
    
}



// 接收到蓝牙数据 先分析
//static dispatch_once_t tiwenOncetoken;
- (void)analyzeData:(NSData *)data  withPeripheral:(CBPeripheral *)aPer
{
    Byte *bytes = (Byte *)[data bytes];
    
    if (bytes[0] == 0xFE && bytes[1] == 0xFD && bytes[2] == 0x1A && bytes[3] == 0xAA && bytes[4] == 0x55 && bytes[5] == 0x5F && bytes[6] == 0x0D && bytes[7] == 0x0A) {
        NSLog(@"连接成功");
    }else if (bytes[0] == 0xFE && bytes[1] == 0xFD && bytes[6] == 0x0D && bytes[7] == 0x0A)
       {
//           dispatch_once(&tiwenOncetoken, ^{
            BOOL booltt = YES;
        
             if (bytes[2] == 0x1A) {
            [self returnTresult:bytes boolyn:booltt];
            }else if (bytes[2] == 0x15) {
            booltt = NO;
            [self returnTresult:bytes boolyn:booltt];
          }
//          });
       }
}

- (void)returnTresult:(Byte *)byte boolyn:(BOOL)booltt
{
    float BodT;
    float tc = 256.0;
    float tz = 10.0;
    float t1;
    
    if (byte[3] == 0x00) {
        t1 = (unsigned char)byte[4] * tc + (unsigned char)byte[5];
        BodT = t1 / tz;
        if (booltt) {
            NSLog(@"00正常目标量测温度测量为：%f C°C", BodT);
        } else {
            NSLog(@"00正常目标量测温度测量为：%f F华氏度", BodT);
        }
    }
    
    if (byte[3] == 0x01) {
        t1 = (unsigned char)byte[4] * tc + (unsigned char)byte[5];
        BodT = t1 / tz;
        if (!booltt) {
            float BodF = (BodT - 32) / 1.8;
            BodT = BodF;
            valueStr = [NSString stringWithFormat:@"%0.0f°C",BodF];
            [self createLabel:valueStr];
            [self.view setNeedsDisplay];
        }
        valueStr = [NSString stringWithFormat:@"%0.01f°C",BodT];
        NSLog(@"01表示额头温度测量为：%f C°C", BodT);
        [self createLabel:valueStr];
        [self.view setNeedsDisplay];
        
        [self getUserParmaterData:[NSString stringWithFormat:@"%0.1f", BodT] selectionValue:0 gaoxueya:nil];
        
    }
    
    
    if(byte[4] == 0x00)
    {
        if ((byte[3] == 0x81) && (byte[5] == 0x01)) {
            NSLog(@"人体模式：量测温度过高.  手机'温度显示位'显示'HI'+人体符号");
        }
        if ((byte[3] == 0x82) && (byte[5] == 0x02)) {
            NSLog(@"人体模式：量测温度过低.  手机'温度显示位'显示'LO'+人体符号");
        }
        if ((byte[3] == 0x83) && (byte[5] == 0x03)) {
            NSLog(@"表示测试错误.  '温度显示位'显示'ErH'(环境温度过高)");
        }
        if ((byte[3] == 0x84) && (byte[5] == 0x04)) {
            NSLog(@"表示测试错误.  '温度显示位'显示'ErL'(环境温度过低)");
        }
        if ((byte[3] == 0x85) && (byte[5] == 0x05)) {
            NSLog(@"表示硬件错误.  '显示位'显示'ErC'");
        }
        if ((byte[3] == 0x86) && (byte[5] == 0x06)) {
            NSLog(@"表示电压低电压.  '显示位'显示'低电压符号'");
        }
        if ((byte[3] == 0x87) && (byte[5] == 0x07)) {
            NSLog(@"物体模式：量测温度过高.  手机'温度显示位'显示'HI'+环境温度符号");
        }
        if ((byte[3] == 0x88) && (byte[5] == 0x08)) {
            NSLog(@"物体模式：量测温度过低.  手机'温度显示位'显示'LO'+环境温度符号");
        }
    }
    
}


@end
